import random

from django import http
from django.shortcuts import redirect
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection

from libs.SMS.celery_sms import sms_app
from libs.captcha.captcha import captcha
from utils import constants
from utils.emails import Email
from utils.response_code import RETCODE


class ImageCodeView(View):
    def get(self, request):
        """
        :param request:
        :param uuid: 唯一标识图片验证码所属于的用户
        :return: image/jpeg
        """
        code_id = request.GET.get('code_id')
        # print(code_id)
        # 生成图片验证码
        _, text, image = captcha.generate_captcha()
        # 保存图片验证码
        redis_conn = get_redis_connection('code')  # 连接Redis数据库
        redis_conn.setex('img_%s' % code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)

        # 响应图片验证码
        return http.HttpResponse(image, content_type='image/jpeg')


class SmsCodeView(View):
    def get(self, request):
        # 获取参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('uuid')
        mobile = request.GET.get('mobile')
        print(image_code_client)
        print(uuid)
        print(mobile)

        # 校验参数
        if not all([image_code_client, uuid]):
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '缺少必传参数'})

        # 创建连接Redis的对象
        redis_conn = get_redis_connection('code')
        # 提取图片验证码
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '验证码已失效'})
        # 删除图片验证码，以防恶意测试图片验证码
        try:
            redis_conn.delete('img_%s', uuid)
        except Exception as e:
            print(e)

        # 对比图形验证码
        image_code_server = image_code_server.decode()  # bytes转字符串
        # 对比小写后的图片验证码
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图片验证码输入有误'})

        # 生成6位数随机短信验证码值
        sms_code = '%06d' % random.randint(0, 999999)
        # 保存短信验证码
        redis_conn.setex('sms_%s' % mobile, constants.IMAGE_CODE_REDIS_EXPIRES, sms_code)

        # 测试避免频繁发送可关闭发送短信验证码功能
        # send_sms(mobile,sms_code)
        # from Celery.task import asd
        # asd(mobile,sms_code)
        sms_app.send_task('send_sms.send_template_sms', args=[mobile, (sms_code, '5')])
        print('>>>发送短信验证码>>>>>', sms_code)

        # 响应结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送短信验证码成功'})
